package com.xzt.bookstore.controller;

import com.xzt.bookstore.common.Result;
import com.xzt.bookstore.dto.CartAddRequest;
import com.xzt.bookstore.dto.CartItemDTO;
import com.xzt.bookstore.entity.Cart;
import com.xzt.bookstore.service.CartService;
import com.xzt.bookstore.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/api/cart")
@RequiredArgsConstructor
public class CartController {
    
    private final CartService cartService;
    private final JwtUtil jwtUtil;
    
    /**
     * 从请求头中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("未登录");
    }
    
    /**
     * 添加商品到购物车
     */
    @PostMapping
    public Result<Cart> addToCart(@Valid @RequestBody CartAddRequest request, HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            Cart cart = cartService.addToCart(userId, request);
            return Result.success("添加成功", cart);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取购物车列表
     */
    @GetMapping
    public Result<List<CartItemDTO>> getCartList(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            List<CartItemDTO> cartList = cartService.getCartList(userId);
            return Result.success(cartList);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    @PutMapping("/{cartId}")
    public Result<Cart> updateQuantity(
            @PathVariable Long cartId,
            @RequestParam Integer quantity,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Cart cart = cartService.updateQuantity(userId, cartId, quantity);
            return Result.success("更新成功", cart);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 从购物车删除商品
     */
    @DeleteMapping("/{cartId}")
    public Result<String> removeFromCart(@PathVariable Long cartId, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            cartService.removeFromCart(userId, cartId);
            return Result.success("删除成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public Result<String> clearCart(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            cartService.clearCart(userId);
            return Result.success("清空成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("清空失败：" + e.getMessage());
        }
    }
}

